package com.zj.log.controller;

import com.zj.log.component.UserRoleAuthentication;
import com.zj.log.domain.Log;
import com.zj.log.enums.CommonEnum;
import com.zj.log.enums.RoleEnum;
import com.zj.log.repository.LogRepository;
import com.zj.log.util.ListPagingUtils;
import com.zj.log.util.ResultVoUtil;
import com.zj.log.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther: zj
 * @Date: 2019/2/5 23:22
 * @Description:
 */
@RestController
public class LogController {
    @Autowired
    LogRepository logRepository;
    @Autowired
    UserRoleAuthentication userRoleAuthentication;

    /**
     * 列出所有的日志，分页(管理员),按时间排序
     * @param request
     * @param pageIndex
     * @return
     */
    @GetMapping("/listAllLogsWithPage")
    public ResultVo listAllLogsWithPage(HttpServletRequest request,
                                        @RequestParam(value = "pageIndex",required = false,defaultValue = "1") Integer pageIndex) {
        //鉴权
        String username = userRoleAuthentication.getUsernameAndAutenticateUserRoleFromRequest( request, RoleEnum.Admin.getMessage() );
        if (Objects.equals( username, CommonEnum.FALSE.getMessage())) {
            return ResultVoUtil.error();
        }

        Sort sort = new Sort( Sort.Direction.DESC, "createDate");
        Pageable pageable = PageRequest.of( pageIndex-1,3,sort);
        List<Log>logs = logRepository.findAll(pageable).getContent();

        return ResultVoUtil.success(logs);
    }

    /**
     * 获取log的总数(管理员)
     * @param request
     * @return
     */
    @GetMapping("/listAllLogsTotal")
    public ResultVo listAllLogsTotal(HttpServletRequest request) {
        //鉴权
        String username = userRoleAuthentication.getUsernameAndAutenticateUserRoleFromRequest( request, RoleEnum.Admin.getMessage() );
        if (Objects.equals( username, CommonEnum.FALSE.getMessage())) {
            return ResultVoUtil.error();
        }

        List<Log>logs = logRepository.findAll();

        return ResultVoUtil.success(logs.size());
    }

}
